package com.kischang.blog.web.actionuser;

import com.kischang.blog.utils.RandomJpeg;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Map;

@Component
@Scope("prototype")
public class UserRegisterCodeImg extends ActionSupport{
	
	private static final long serialVersionUID = -7154390125206466492L;
	public static final String REG_CODE = "codeStr";
	
	
	
	private InputStream inputStream;
	public String execute() throws Exception {
		RandomJpeg randomJpeg = new RandomJpeg();
		BufferedImage img = randomJpeg.getNewDefaultImage();
		ImageOutputStream imOut; 
		ByteArrayOutputStream bs = new ByteArrayOutputStream();  
		imOut = ImageIO.createImageOutputStream(bs); 
        ImageIO.write(img, "png",imOut);
        this.inputStream = new ByteArrayInputStream(bs.toByteArray());
        
        String codeStr = randomJpeg.getCodeStr();
        Map<String ,Object> session = ActionContext.getContext().getSession();
		session.put(REG_CODE, codeStr);
        return SUCCESS;
	}
	
	public static void failureCode(){
		ActionContext.getContext().getSession().put(REG_CODE, "");
	}
	public InputStream getInputStream() {
		return inputStream;
	}
	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}
}
